package com.itheima.controller;

import com.itheima.bean.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            // 设置编码
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");

            // 获取请求参数
            Map<String, String[]> map = request.getParameterMap();

            // 封装到User对象
            User user = new User();
            BeanUtils.populate(user,map);

            // 调用service查询
            UserService service = new UserServiceImpl();
            User existUser = service.login(user);

            // 判断用户是否存在
            if (existUser!=null){
                // 登陆成功
                request.getSession().setAttribute("username",user.getUsername());
                response.getWriter().write("true");
            }else {
                response.getWriter().write("false");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
